package cn.com.khproc;

import com.elite.groovy.kh.KHUtil;
import com.elite.groovy.util.EliteBean;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.sql.DataSource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 
 * @Title: jsonCallProcedure
 * @Description: 将预定义的Json字符串调用对于存储过程
 * @author: LiJuntao
 * @date 2019-12-18 下午9:15:40
 *
 */
public class jsonCallProcedure {
	private static final Log log = LogFactory.getLog(jsonCallProcedure.class);

	public static String doService(String SyncJson) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Long useStartTime = System.currentTimeMillis();
		Long useEndTime = null;
		String useTimeInfo = "";
		EliteBean eliteBean = new EliteBean();

		DataSource dataSource1 = eliteBean.getDataSource();

		String SyncType = "";
		JSONObject reJson = JSONObject.fromObject("{\"code\":0,\"message\":\"处理失败\"}");

		if (JsonValidator.main(SyncJson) && SyncJson != null && SyncJson.length() > 0) {

			SyncJson = transToLower.ToLower(SyncJson);
			log.info("转换Json格式结果:" + SyncJson);

			JSONObject json = JSONObject.fromObject(SyncJson);
			try {
				SyncType = json.getString("sync_type").toLowerCase();

				log.info("SyncType:" + SyncType + " StartTime:" + df.format(new Date()));

			} catch (Exception e) {
				log.error("getString sync_type Exception:" + e.getMessage());
				SyncType = "";
			}

			if (!KHUtil.isNull(SyncType)) {

				List<Map<String, Object>> paramList = GetParameter.doService(dataSource1, SyncType);

				if (paramList.size() > 0) {
					String callResult = callProcedure.doService("dataSource", SyncType, paramList, SyncJson);

					if (!KHUtil.isNull(callResult)) {
						reJson.put("code", 1);
						reJson.put("message", "调用操作成功");
						reJson.put("data", callResult);
					} else {
						reJson.put("message", "数据处理入库失败,返回值异常");
					}

				} else {
					reJson.put("message", "Elite暂未支持该同步类型Sync_Type");
				}

			} else {
				reJson.put("message", "同步Elite失败,Json信息中未定义同步类型Sync_Type:" + SyncType);
			}
		} else if (SyncJson == null || SyncJson.length() <= 0) {
			reJson.put("message", "同步Elite失败,未发现提交Json数据信息");

		} else {
			reJson.put("message", "同步下发处理Error Info:JSON格式问题(不支持)");

		}

		useEndTime = System.currentTimeMillis();
		useTimeInfo = Long.toString(useEndTime - useStartTime);

		log.info("Result_Json:" + reJson.toString() + " 处理时长(毫秒):" + useTimeInfo + " EndTime:" + df.format(new Date()));

		return reJson.toString();
	}
}